using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace FrameWork.Inventory
{
    /// <summary>
    /// 每次激活时候，获取背包内所有物品，展示在UI页面中
    /// </summary>
    public class InventoryToShopView : MonoBehaviour
    {
        [Header("图标挂载父物体")]
        [SerializeField] private GameObject objUI;
        [Header("物品格子预制体")]
        [SerializeField] private Slot slotPrefab;
        [Header("背包SO文件")]
        [SerializeField] private InventorySO inventorySO;

        private void OnEnable()
        {
            inventorySO.OnInventoryUpdate += FillItemToUI;
            // 0.5S 后执行
            Invoke("FillItemToUI", 0.5f);
            // FillItemToUI();
        }

        private void OnDisable()
        {
            inventorySO.OnInventoryUpdate -= FillItemToUI;
        }

        private void FillItemToUI()
        {
            inventorySO.UpdateView();
        }

        /// <summary>
        /// 获取背包内所有的物品
        /// 填充所有物品格子
        /// </summary>
        public void FillItemToUI(Dictionary<int, InventoryItem> inventoryState)
        {
            if (inventoryState == null)
            {
                Debug.LogError("inventoryState 为 null！");
                return;
            }
            
            ClearChild();
            foreach (var variable in inventorySO.GetCurrentInventoryItem())
            {
                if (!variable.IsEmpty)
                {
                    Slot slot = Instantiate(slotPrefab, Vector3.zero, Quaternion.identity);
                    slot.transform.SetParent(objUI.transform);
                    slot.ResetSlot();
                    slot.SetSlot(variable);
                }
                else
                {
                    Debug.Log(variable + "是空的");
                    return;
                }
            }
        }

        /// <summary>
        /// 清空子物品
        /// </summary>
        private void ClearChild()
        {
            foreach (Transform child in objUI.transform)
            {
                // 销毁子对象，包括其所有组件
                Destroy(child.gameObject);
            }
        }
    }

}